﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using WXYW.Entities;
using WXYW.DAL;
using WXYW.Model;

namespace WXYW.BLL
{
    public class SparePartService : RepositoryBase
    {
        public void AddSparePart(string materialNO, int productTypeID, string modelNumber, string versionNumber, int count, string stockType,
            string marketPrice, string sparePartPrice, string status, int enterStationID, User currentOperator, string stockPlace,
            string rkNO, string rkComment)
        {
            SparePart sparePart = GetEntities<SparePart>().Where(s => s.ModelNumber.Equals(modelNumber) && s.VersionNumber.Equals(versionNumber) && s.StockType.Equals(stockType)).FirstOrDefault();
            ServiceStation targetServiceStationEntity = GetEntities<ServiceStation>().Where(s => s.ID == enterStationID).FirstOrDefault();
            if (sparePart == null)
            {
                SparePart newSparePartEntity = new SparePart();
                //newSparePartEntity.Description = description;
                newSparePartEntity.LastUpdateBy = currentOperator.UserID;
                newSparePartEntity.LastUpdated = DateTime.Now;
                newSparePartEntity.MarketPrice = marketPrice;
                newSparePartEntity.MaterialNO = materialNO;
                newSparePartEntity.ModelNumber = modelNumber;
                newSparePartEntity.Count = count;
                newSparePartEntity.ProductType = GetEntities<ProductType>().Where(p => p.ProductTypeID == productTypeID).FirstOrDefault();
                newSparePartEntity.ServiceStation = targetServiceStationEntity;
                newSparePartEntity.SparePartPrice = sparePartPrice;
                //newSparePartEntity.Status = status;
                newSparePartEntity.StockType = stockType;
                if (status.Equals("良品"))
                {
                    newSparePartEntity.GoodCount = count;
                }
                else
                {
                    newSparePartEntity.BadCount = count;
                }
                newSparePartEntity.VersionNumber = versionNumber;
                newSparePartEntity.StockPlace = stockPlace;
                newSparePartEntity.EnterNO = rkNO;
                newSparePartEntity.EnterComment = rkComment;
                InsertEntity(newSparePartEntity);
            }
            else
            {
                sparePart.Count += count;
                if (status.Equals("良品"))
                {
                    sparePart.GoodCount += count;
                }
                else
                {
                    sparePart.BadCount += count;
                }
                sparePart.StockType = stockType;
                sparePart.LastUpdateBy = currentOperator.UserID;
                sparePart.LastUpdated = DateTime.Now;
                sparePart.MaterialNO = materialNO;                
                UpdateEntity(sparePart);
            }

            SparePartRecord recordEntity = new SparePartRecord();
            if (status.Equals("良品"))
            {
                recordEntity.GoodCount = count;
            }
            else
            {
                recordEntity.BadCount = count;            
            }
            recordEntity.Comment = "";
            recordEntity.EnterCount = count;
            recordEntity.EnterStorageDate = DateTime.Now;
            recordEntity.ModelNumber = modelNumber;
            recordEntity.VersionNumer = versionNumber;
            recordEntity.OperationType = "新增";
            recordEntity.Operator = currentOperator.UserID;
            recordEntity.ServiceStation = targetServiceStationEntity;
            InsertEntity(recordEntity);
        }
        
        public IQueryable<SparePart> GetAllSpareParts()
        {
            return GetEntities<SparePart>();
        }
		
		public List<SparePart> GetSparePartByProductTypeID(int typeNumber)
        {
            return GetEntities<SparePart>(s => s.ProductType.ProductTypeID==typeNumber).ToList();
        }

        public List<SparePartModel> GetAllSparePartModel(string keyWord)
        {
            List<SparePartModel> sparePartModelList = new List<SparePartModel>();
            IQueryable<SparePart> sparePartEntities = GetEntities<SparePart>();
            
            foreach (SparePart sparePartEntity in sparePartEntities)
            {
                SparePartModel sparePartModel = new SparePartModel();
                sparePartModel.ID = sparePartEntity.ID.ToString();
                if (sparePartEntity.Count.HasValue)
                {
                    sparePartModel.Count = sparePartEntity.Count.Value.ToString();
                }
                else
                {
                    sparePartModel.Count = "0";
                }
                sparePartModel.MaterialNO = sparePartEntity.MaterialNO;
                sparePartModel.ModelNumber = sparePartEntity.ModelNumber;
                sparePartModel.Description = sparePartEntity.Description;

                if (!sparePartEntity.ServiceStationReference.IsLoaded)
                {
                    sparePartEntity.ServiceStationReference.Load();
                }
                sparePartModel.StorageStation = sparePartEntity.ServiceStation.Name;


                if (!sparePartEntity.ProductTypeReference.IsLoaded)
                {
                    sparePartEntity.ProductTypeReference.Load();
                }

                sparePartModel.ProductCategory = GetEntities<ProductClass>().Where(p => p.ID == sparePartEntity.ProductType.ProductTypeID).FirstOrDefault().Name;  //sparePartEntity.ProductType.ProductTypeName;
                sparePartModel.VersionNumber = sparePartEntity.VersionNumber;
                sparePartModel.GoodCount = sparePartEntity.GoodCount.ToString();
                sparePartModel.BadCount = sparePartEntity.BadCount.ToString();
                sparePartModel.MarketPrice = sparePartEntity.MarketPrice;
                sparePartModel.SparePartPrice = sparePartEntity.SparePartPrice;
                sparePartModel.StockType = sparePartEntity.StockType;
                sparePartModel.RepairTimes = sparePartEntity.RepairTimes.ToString();
                sparePartModel.UseTimes = sparePartEntity.UseTimes.ToString();

                if (!sparePartEntity.ServiceStationReference.IsLoaded)
                {
                    sparePartEntity.ServiceStationReference.Load();
                }
                sparePartModel.Station = sparePartEntity.ServiceStation.Name;
                sparePartModel.EnterComment = sparePartEntity.EnterComment;
                sparePartModel.EnterNO = sparePartEntity.EnterNO;
                sparePartModel.StockPlace = sparePartEntity.StockPlace;
                sparePartModelList.Add(sparePartModel);
            }

            if (!string.IsNullOrEmpty(keyWord))
            {
                sparePartModelList = sparePartModelList.Where(s => 
                   (!string.IsNullOrEmpty(s.Description) && s.Description.Contains(keyWord)) ||
                   (!string.IsNullOrEmpty(s.EnterComment) && s.EnterComment.Contains(keyWord)) ||
                   (!string.IsNullOrEmpty(s.EnterNO) && s.EnterNO.Contains(keyWord)) ||
                   (!string.IsNullOrEmpty(s.MaterialNO) && s.MaterialNO.Contains(keyWord)) ||
                   (!string.IsNullOrEmpty(s.ModelNumber) && s.ModelNumber.Contains(keyWord)) ||
                   (!string.IsNullOrEmpty(s.ProductCategory) && s.ProductCategory.Contains(keyWord)) ||
                   (!string.IsNullOrEmpty(s.Station) && s.Station.Contains(keyWord)) ||
                   (!string.IsNullOrEmpty(s.StockPlace) && s.StockPlace.Contains(keyWord)) ||
                   (!string.IsNullOrEmpty(s.StockType) && s.StockType.Contains(keyWord)) ||
                   (!string.IsNullOrEmpty(s.StorageStation) && s.StorageStation.Contains(keyWord)) ||
                   (!string.IsNullOrEmpty(s.VersionNumber) && s.VersionNumber.Contains(keyWord)) ||
                   (!string.IsNullOrEmpty(s.UseTimes) && s.UseTimes.Contains(keyWord)) ||
                   (!string.IsNullOrEmpty(s.GoodCount) && s.GoodCount.Contains(keyWord)) ||
                   (!string.IsNullOrEmpty(s.BadCount) && s.BadCount.Contains(keyWord)) ||
                   (!string.IsNullOrEmpty(s.Count) && s.Count.Contains(keyWord))).ToList();
            }
            return sparePartModelList;
        }

        public List<SparePartModel> GetSparePartModelByPlatform(string keyWord, int platformID)
        {
            List<SparePartModel> sparePartModelList = new List<SparePartModel>();
            IQueryable<SparePart> sparePartEntities = GetEntities<SparePart>().Where(s=>s.ServiceStation.ID == platformID);

            foreach (SparePart sparePartEntity in sparePartEntities)
            {
                SparePartModel sparePartModel = new SparePartModel();
                sparePartModel.ID = sparePartEntity.ID.ToString();
                if (sparePartEntity.Count.HasValue)
                {
                    sparePartModel.Count = sparePartEntity.Count.Value.ToString();
                }
                else
                {
                    sparePartModel.Count = "0";
                }
                sparePartModel.MaterialNO = sparePartEntity.MaterialNO;
                sparePartModel.ModelNumber = sparePartEntity.ModelNumber;
                sparePartModel.Description = sparePartEntity.Description;

                if (!sparePartEntity.ServiceStationReference.IsLoaded)
                {
                    sparePartEntity.ServiceStationReference.Load();
                }
                sparePartModel.StorageStation = sparePartEntity.ServiceStation.Name;


                if (!sparePartEntity.ProductTypeReference.IsLoaded)
                {
                    sparePartEntity.ProductTypeReference.Load();
                }

                sparePartModel.ProductCategory = GetEntities<ProductClass>().Where(p => p.ID == sparePartEntity.ProductType.ProductTypeID).FirstOrDefault().Name;  //sparePartEntity.ProductType.ProductTypeName;
                sparePartModel.VersionNumber = sparePartEntity.VersionNumber;
                sparePartModel.GoodCount = sparePartEntity.GoodCount.ToString();
                sparePartModel.BadCount = sparePartEntity.BadCount.ToString();
                sparePartModel.MarketPrice = sparePartEntity.MarketPrice;
                sparePartModel.SparePartPrice = sparePartEntity.SparePartPrice;
                sparePartModel.StockType = sparePartEntity.StockType;
                sparePartModel.RepairTimes = sparePartEntity.RepairTimes.ToString();
                sparePartModel.UseTimes = sparePartEntity.UseTimes.ToString();

                if (!sparePartEntity.ServiceStationReference.IsLoaded)
                {
                    sparePartEntity.ServiceStationReference.Load();
                }
                sparePartModel.Station = sparePartEntity.ServiceStation.Name;
                sparePartModel.EnterComment = sparePartEntity.EnterComment;
                sparePartModel.EnterNO = sparePartEntity.EnterNO;
                sparePartModel.StockPlace = sparePartEntity.StockPlace;
                sparePartModelList.Add(sparePartModel);
            }

            if (!string.IsNullOrEmpty(keyWord))
            {
                sparePartModelList = sparePartModelList.Where(s =>
                   (!string.IsNullOrEmpty(s.Description) && s.Description.Contains(keyWord)) ||
                   (!string.IsNullOrEmpty(s.EnterComment) && s.EnterComment.Contains(keyWord)) ||
                   (!string.IsNullOrEmpty(s.EnterNO) && s.EnterNO.Contains(keyWord)) ||
                   (!string.IsNullOrEmpty(s.MaterialNO) && s.MaterialNO.Contains(keyWord)) ||
                   (!string.IsNullOrEmpty(s.ModelNumber) && s.ModelNumber.Contains(keyWord)) ||
                   (!string.IsNullOrEmpty(s.ProductCategory) && s.ProductCategory.Contains(keyWord)) ||
                   (!string.IsNullOrEmpty(s.Station) && s.Station.Contains(keyWord)) ||
                   (!string.IsNullOrEmpty(s.StockPlace) && s.StockPlace.Contains(keyWord)) ||
                   (!string.IsNullOrEmpty(s.StockType) && s.StockType.Contains(keyWord)) ||
                   (!string.IsNullOrEmpty(s.StorageStation) && s.StorageStation.Contains(keyWord)) ||
                   (!string.IsNullOrEmpty(s.VersionNumber) && s.VersionNumber.Contains(keyWord)) ||
                   (!string.IsNullOrEmpty(s.UseTimes) && s.UseTimes.Contains(keyWord)) ||
                   (!string.IsNullOrEmpty(s.GoodCount) && s.GoodCount.Contains(keyWord)) ||
                   (!string.IsNullOrEmpty(s.BadCount) && s.BadCount.Contains(keyWord)) ||
                   (!string.IsNullOrEmpty(s.Count) && s.Count.Contains(keyWord))).ToList();
            }
            return sparePartModelList;
        }

        public SparePart GetSparePartEntityByID(int id)
        {
            return GetEntities<SparePart>().Where(s => s.ID == id).FirstOrDefault();
        }

        public void TransferSparePart(int sparePartID, int targetPlatformID, string status, int count, User currentOperator)
        {
            SparePart sourceSparePartEntity = GetEntities<SparePart>().Where(p => p.ID == sparePartID).FirstOrDefault();
            switch (status)
            {
                case "良品":
                    sourceSparePartEntity.GoodCount -= count;
                    break;
                case "不良品":
                    sourceSparePartEntity.BadCount -= count;
                    break;
            }
            sourceSparePartEntity.Count -= count;
            sourceSparePartEntity.LastUpdated = DateTime.Now;
            sourceSparePartEntity.LastUpdateBy = currentOperator.UserID;
            UpdateEntity(sourceSparePartEntity);


            // 如果是出售或者报废的话只记出库记录
            if (targetPlatformID < 0)
            {
                SparePartRecord saleOrDiscardRecordEntity = new SparePartRecord();
                switch (status)
                {
                    case "良品":
                        saleOrDiscardRecordEntity.GoodCount = count;
                        break;
                    case "不良品":
                        saleOrDiscardRecordEntity.BadCount = count;
                        break;
                }
                saleOrDiscardRecordEntity.OutCount = count;
                saleOrDiscardRecordEntity.OutStorageDate = DateTime.Now;
                if (!sourceSparePartEntity.ServiceStationReference.IsLoaded)
                {
                    sourceSparePartEntity.ServiceStationReference.Load();
                }
                saleOrDiscardRecordEntity.ServiceStation = sourceSparePartEntity.ServiceStation;
                saleOrDiscardRecordEntity.Operator = currentOperator.UserID;
                saleOrDiscardRecordEntity.ModelNumber = sourceSparePartEntity.ModelNumber;
                saleOrDiscardRecordEntity.VersionNumer = sourceSparePartEntity.VersionNumber;
                saleOrDiscardRecordEntity.OperationType = string.Format("{0}->{1}", sourceSparePartEntity.ServiceStation.Name, targetPlatformID == -1 ? "出售" : "报废");
                InsertEntity(saleOrDiscardRecordEntity);
                return;
            }

            SparePart targetSparePartEntity = GetEntities<SparePart>().Where(p => p.ModelNumber.Equals(sourceSparePartEntity.ModelNumber) &&
                p.VersionNumber.Equals(sourceSparePartEntity.VersionNumber) && p.StockType.Equals(sourceSparePartEntity.StockType) && p.ServiceStation.ID == targetPlatformID).FirstOrDefault();
            ServiceStation targetStationEntity = GetEntities<ServiceStation>().Where(s => s.ID == targetPlatformID).FirstOrDefault();
            if (targetSparePartEntity != null)
            {
                targetSparePartEntity.LastUpdateBy = currentOperator.UserID;
                targetSparePartEntity.LastUpdated = DateTime.Now;
                targetSparePartEntity.Count += count;
                switch (status)
                {
                    case "良品":
                        targetSparePartEntity.GoodCount += count;
                        break;
                    case "不良品":
                        targetSparePartEntity.BadCount += count;
                        break;
                }
                UpdateEntity(targetSparePartEntity);
            }
            else
            {
                targetSparePartEntity = new SparePart();
                targetSparePartEntity.Count = count;
                switch (status)
                {
                    case "良品":
                        targetSparePartEntity.GoodCount = count;
                        break;
                    case "不良品":
                        targetSparePartEntity.BadCount = count;
                        break;
                }
                targetSparePartEntity.LastUpdateBy = currentOperator.UserID;
                targetSparePartEntity.LastUpdated = DateTime.Now;
                targetSparePartEntity.MarketPrice = sourceSparePartEntity.MarketPrice;
                targetSparePartEntity.ModelNumber = sourceSparePartEntity.ModelNumber;
                if (!sourceSparePartEntity.ProductTypeReference.IsLoaded)
                {
                    sourceSparePartEntity.ProductTypeReference.Load();
                }
                targetSparePartEntity.ProductType = sourceSparePartEntity.ProductType;
                targetSparePartEntity.SparePartPrice = sourceSparePartEntity.SparePartPrice;
                targetSparePartEntity.StockType = sourceSparePartEntity.StockType;
                targetSparePartEntity.VersionNumber = sourceSparePartEntity.VersionNumber;                
                targetSparePartEntity.ServiceStation = targetStationEntity;
                InsertEntity(targetSparePartEntity);
            }

            // 出库记录
            SparePartRecord outSparePartRecordEntity = new SparePartRecord();
            switch (status)
            {
                case "良品":
                    outSparePartRecordEntity.GoodCount = count;
                    break;
                case "不良品":
                    outSparePartRecordEntity.BadCount = count;
                    break;
            }
            outSparePartRecordEntity.OutCount = count;
            outSparePartRecordEntity.OutStorageDate = DateTime.Now;
            if (!sourceSparePartEntity.ServiceStationReference.IsLoaded)
            {
                sourceSparePartEntity.ServiceStationReference.Load();
            }
            outSparePartRecordEntity.ServiceStation = sourceSparePartEntity.ServiceStation;
            outSparePartRecordEntity.Operator = currentOperator.UserID;
            outSparePartRecordEntity.ModelNumber = sourceSparePartEntity.ModelNumber;
            outSparePartRecordEntity.VersionNumer = sourceSparePartEntity.VersionNumber;
            outSparePartRecordEntity.OperationType = string.Format("{0}->{1}", sourceSparePartEntity.ServiceStation.Name, targetStationEntity.Name);
            InsertEntity(outSparePartRecordEntity);

            //入库记录
            SparePartRecord inSparePartRecordEntity = new SparePartRecord();
            switch (status)
            {
                case "良品":
                    inSparePartRecordEntity.GoodCount = count;
                    break;
                case "不良品":
                    inSparePartRecordEntity.BadCount = count;
                    break;
            }
            inSparePartRecordEntity.EnterCount = count;
            inSparePartRecordEntity.EnterStorageDate = DateTime.Now;
            inSparePartRecordEntity.ServiceStation = targetStationEntity;
            inSparePartRecordEntity.Operator = currentOperator.UserID;
            inSparePartRecordEntity.ModelNumber = sourceSparePartEntity.ModelNumber;
            inSparePartRecordEntity.VersionNumer = sourceSparePartEntity.VersionNumber;
            inSparePartRecordEntity.OperationType = string.Format("{0}->{1}", sourceSparePartEntity.ServiceStation.Name, targetStationEntity.Name);
            InsertEntity(inSparePartRecordEntity);
        }

        public List<SparePartRecordModel> GetRecords(int platformID, int sparePartID)
        {
            List<SparePartRecordModel> recordsModel = new List<SparePartRecordModel>();
            SparePart sparePartEntity = GetEntities<SparePart>().Where(s=>s.ID == sparePartID).FirstOrDefault();
            if (!sparePartEntity.ServiceStationReference.IsLoaded)
            {
                sparePartEntity.ServiceStationReference.Load();
            }
            IQueryable<SparePartRecord> recordEntities = null;
            if (platformID == 0)
            {
                recordEntities = GetEntities<SparePartRecord>().Where(s => s.ModelNumber.Equals(sparePartEntity.ModelNumber) &&
                s.VersionNumer.Equals(sparePartEntity.VersionNumber) && s.ServiceStation.ID == sparePartEntity.ServiceStation.ID);
            }
            else
            {
                recordEntities = GetEntities<SparePartRecord>().Where(s => s.ModelNumber.Equals(sparePartEntity.ModelNumber) &&
                s.VersionNumer.Equals(sparePartEntity.VersionNumber) && s.ServiceStation.ID == platformID && 
                s.ServiceStation.ID == sparePartEntity.ServiceStation.ID);
            }

            foreach (SparePartRecord recordEntity in recordEntities)
            {
                SparePartRecordModel sparePartRecordModel = new SparePartRecordModel();
                sparePartRecordModel.BadCount = recordEntity.BadCount.HasValue? recordEntity.BadCount.Value.ToString() : "";
                sparePartRecordModel.Comment = recordEntity.Comment;
                sparePartRecordModel.EnterCount = recordEntity.EnterCount.HasValue? recordEntity.EnterCount.Value.ToString(): "";
                sparePartRecordModel.EnterDateTime = recordEntity.EnterStorageDate.HasValue ? recordEntity.EnterStorageDate.Value.ToString() : "";
                sparePartRecordModel.GoodCount = recordEntity.GoodCount.HasValue? recordEntity.GoodCount.Value.ToString(): "";
                sparePartRecordModel.ID = recordEntity.RecordID.ToString();
                sparePartRecordModel.ModelNumber = recordEntity.ModelNumber;
                sparePartRecordModel.OperationType = recordEntity.OperationType;
                User userEntity = GetEntities<User>().Where(u => u.UserID == recordEntity.Operator.Value).FirstOrDefault();
                if (userEntity != null)
                {
                    sparePartRecordModel.Operator = userEntity.UserName;
                }
                sparePartRecordModel.OutCount = recordEntity.OutCount.HasValue ? recordEntity.OutCount.Value.ToString() : "";
                sparePartRecordModel.OutDate = recordEntity.OutStorageDate.HasValue ? recordEntity.OutStorageDate.Value.ToString() : "";
                if (!recordEntity.ServiceStationReference.IsLoaded)
                {
                    recordEntity.ServiceStationReference.Load();
                }
                sparePartRecordModel.Platform = recordEntity.ServiceStation.Name;
                sparePartRecordModel.tranferCount = recordEntity.TransferCount.HasValue ? recordEntity.TransferCount.Value.ToString() : "";
                sparePartRecordModel.transferDateTime = recordEntity.TransferDate.HasValue ? recordEntity.TransferDate.Value.ToString() : "";
                sparePartRecordModel.VersionNumber = recordEntity.VersionNumer;
                recordsModel.Add(sparePartRecordModel);
            }
            return recordsModel;
        }

        public void TransferSparePartInPlatform(string transferType, int sparePartID, int transferCount, string comment, User currentOperator)
        {
            SparePart sparePartEntity = GetEntities<SparePart>().Where(s => s.ID == sparePartID).FirstOrDefault();
            if (!sparePartEntity.ServiceStationReference.IsLoaded)
            {
                sparePartEntity.ServiceStationReference.Load();
            }
            SparePartRecord sparePartRecordEntity = new SparePartRecord();
            switch (transferType)
            {
                case "良品->非良品":
                    sparePartEntity.BadCount += transferCount;
                    sparePartEntity.GoodCount -= transferCount;
                    sparePartEntity.LastUpdateBy = currentOperator.UserID;
                    sparePartEntity.LastUpdated = DateTime.Now;
                    UpdateEntity(sparePartEntity);
                    
                    sparePartRecordEntity.BadCount = transferCount;
                    sparePartRecordEntity.Comment = comment;
                    sparePartRecordEntity.ModelNumber = sparePartEntity.ModelNumber;
                    sparePartRecordEntity.VersionNumer = sparePartEntity.VersionNumber;
                    sparePartRecordEntity.TransferCount = transferCount;
                    sparePartRecordEntity.TransferDate = DateTime.Now;
                    sparePartRecordEntity.Operator = currentOperator.UserID;
                    
                    sparePartRecordEntity.ServiceStation = sparePartEntity.ServiceStation;
                    sparePartRecordEntity.OperationType = transferType;
                    InsertEntity(sparePartRecordEntity);
                    break;
                case "非良品->良品":
                    sparePartEntity.BadCount -= transferCount;
                    sparePartEntity.GoodCount += transferCount;
                    sparePartEntity.LastUpdateBy = currentOperator.UserID;
                    sparePartEntity.LastUpdated = DateTime.Now;
                    UpdateEntity(sparePartEntity);

                    sparePartRecordEntity.GoodCount = transferCount;
                    sparePartRecordEntity.Comment = comment;
                    sparePartRecordEntity.ModelNumber = sparePartEntity.ModelNumber;
                    sparePartRecordEntity.VersionNumer = sparePartEntity.VersionNumber;
                    sparePartRecordEntity.TransferCount = transferCount;
                    sparePartRecordEntity.TransferDate = DateTime.Now;
                    sparePartRecordEntity.Operator = currentOperator.UserID;
                    sparePartRecordEntity.ServiceStation = sparePartEntity.ServiceStation;
                    sparePartRecordEntity.OperationType = transferType;
                    InsertEntity(sparePartRecordEntity);
                    break;
                case "退库":         
                    ServiceStationService serviceStationService = new ServiceStationService();
                    ServiceStation headServiceStationEntity = serviceStationService.GetHeadServiceStation();
                    SparePart sparePartInHeadServiceStationEntity = GetEntities<SparePart>().Where(s=>s.ServiceStation.ID == headServiceStationEntity.ID &&
                        s.ModelNumber.Equals(sparePartEntity.ModelNumber) && s.VersionNumber.Equals(sparePartEntity.VersionNumber) && s.StockType.Equals(sparePartEntity.StockType)).FirstOrDefault();
                    if (sparePartInHeadServiceStationEntity != null)
                    {
                        sparePartInHeadServiceStationEntity.Count += sparePartEntity.Count;
                        sparePartInHeadServiceStationEntity.GoodCount += sparePartEntity.GoodCount;
                        sparePartInHeadServiceStationEntity.BadCount += sparePartEntity.BadCount;
                        sparePartInHeadServiceStationEntity.LastUpdated = DateTime.Now;
                        sparePartInHeadServiceStationEntity.LastUpdateBy = currentOperator.UserID;
                        UpdateEntity(sparePartInHeadServiceStationEntity);
                    }
                    else
                    {
                        sparePartInHeadServiceStationEntity = new SparePart();
                        sparePartInHeadServiceStationEntity.BadCount = sparePartEntity.BadCount;
                        sparePartInHeadServiceStationEntity.Count = sparePartEntity.Count;
                        sparePartInHeadServiceStationEntity.Description = sparePartEntity.Description;
                        sparePartInHeadServiceStationEntity.GoodCount = sparePartEntity.GoodCount;
                        sparePartInHeadServiceStationEntity.LastUpdateBy = currentOperator.UserID;
                        sparePartInHeadServiceStationEntity.LastUpdated = DateTime.Now;
                        sparePartInHeadServiceStationEntity.MarketPrice = sparePartEntity.MarketPrice;
                        sparePartInHeadServiceStationEntity.MaterialNO = sparePartEntity.MaterialNO;
                        sparePartInHeadServiceStationEntity.ModelNumber = sparePartEntity.ModelNumber;
                        if (!sparePartEntity.ProductTypeReference.IsLoaded)
                        {
                            sparePartEntity.ProductTypeReference.Load();
                        }
                        sparePartInHeadServiceStationEntity.ProductType = sparePartEntity.ProductType;
                        sparePartInHeadServiceStationEntity.RepairTimes = sparePartEntity.RepairTimes;
                        sparePartInHeadServiceStationEntity.ServiceStation = headServiceStationEntity;
                        sparePartInHeadServiceStationEntity.SparePartPrice = sparePartEntity.SparePartPrice;
                        sparePartInHeadServiceStationEntity.StockType = sparePartEntity.StockType;
                        sparePartInHeadServiceStationEntity.UseTimes = sparePartEntity.UseTimes;
                        sparePartInHeadServiceStationEntity.VersionNumber = sparePartEntity.VersionNumber;
                        InsertEntity(sparePartInHeadServiceStationEntity);
                    }

                    SparePartRecord outRecord = new SparePartRecord();
                    outRecord.TransferCount = sparePartEntity.Count;
                    outRecord.TransferDate = DateTime.Now;
                    outRecord.GoodCount = sparePartEntity.GoodCount;
                    outRecord.BadCount = sparePartEntity.BadCount;
                    outRecord.ModelNumber = sparePartEntity.ModelNumber;
                    outRecord.VersionNumer = sparePartEntity.VersionNumber;
                    outRecord.Operator = currentOperator.UserID;
                    outRecord.Comment = comment;
                    outRecord.OperationType = "退库";
                    outRecord.ServiceStation = sparePartEntity.ServiceStation;
                    InsertEntity(outRecord);

                    SparePartRecord inRecord = new SparePartRecord();
                    inRecord.TransferCount = sparePartEntity.Count;
                    inRecord.GoodCount = sparePartEntity.GoodCount;
                    inRecord.BadCount = sparePartEntity.BadCount;
                    inRecord.Comment = comment;
                    inRecord.TransferDate = DateTime.Now;
                    inRecord.ModelNumber = sparePartEntity.ModelNumber;
                    inRecord.VersionNumer = sparePartEntity.VersionNumber;
                    inRecord.ServiceStation = headServiceStationEntity;
                    inRecord.OperationType = string.Format("{0}->退库", sparePartEntity.ServiceStation.Name);
                    inRecord.Operator = currentOperator.UserID;
                    InsertEntity(inRecord);

                    sparePartEntity.Count = 0;
                    sparePartEntity.GoodCount = 0;
                    sparePartEntity.BadCount = 0;
                    sparePartEntity.LastUpdateBy = currentOperator.UserID;
                    sparePartEntity.LastUpdated = DateTime.Now;
                    UpdateEntity(sparePartEntity);
                    break;
                case "报废":
                    sparePartEntity.BadCount += transferCount;
                    sparePartEntity.GoodCount -= transferCount;
                    sparePartEntity.LastUpdateBy = currentOperator.UserID;
                    sparePartEntity.LastUpdated = DateTime.Now;
                    UpdateEntity(sparePartEntity);

                    sparePartRecordEntity.BadCount = transferCount;
                    sparePartRecordEntity.Comment = comment;
                    sparePartRecordEntity.ModelNumber = sparePartEntity.ModelNumber;
                    sparePartRecordEntity.VersionNumer = sparePartEntity.VersionNumber;
                    sparePartRecordEntity.TransferCount = transferCount;
                    sparePartRecordEntity.TransferDate = DateTime.Now;
                    sparePartRecordEntity.Operator = currentOperator.UserID;
                    sparePartRecordEntity.ServiceStation = sparePartEntity.ServiceStation;
                    sparePartRecordEntity.OperationType = transferType;
                    InsertEntity(sparePartRecordEntity);
                    break;

            }
        }

        public void SaveLendRecord(int sparePartID, int lendCount, string customerName, string contactPerson, string phone, string email, 
            string address, DateTime deadline, User currentOperator, string lendReason)
        {
            SparePart sparePartEntity = GetEntities<SparePart>().Where(s => s.ID == sparePartID).FirstOrDefault();
            sparePartEntity.GoodCount -= lendCount;
            sparePartEntity.Count -= lendCount;
            sparePartEntity.LastUpdated = DateTime.Now;
            sparePartEntity.LastUpdateBy = currentOperator.UserID;
            UpdateEntity(sparePartEntity);

            if (!sparePartEntity.ServiceStationReference.IsLoaded)
            {
                sparePartEntity.ServiceStationReference.Load();
            }
            if (!sparePartEntity.ProductTypeReference.IsLoaded)
            {
                sparePartEntity.ProductTypeReference.Load();
            }
            if (!currentOperator.ServiceStationReference.IsLoaded)
            {
                currentOperator.ServiceStationReference.Load();
            }

            //借入单位备件存储信息
            //SparePart sparePart = GetEntities<SparePart>().Where(s => s.ModelNumber.Equals(sparePartEntity.ModelNumber) 
            //    && s.VersionNumber.Equals(sparePartEntity.VersionNumber) && s.StockType.Equals(sparePartEntity.StockType)
            //    && s.ServiceStation.ID == currentOperator.ServiceStation.ID).FirstOrDefault();
            //ServiceStation targetServiceStationEntity = currentOperator.ServiceStation;
            //if (sparePart == null)
            //{
            //    SparePart newSparePartEntity = new SparePart();
            //    newSparePartEntity.LastUpdateBy = currentOperator.UserID;
            //    newSparePartEntity.LastUpdated = DateTime.Now;
            //    newSparePartEntity.MarketPrice = sparePartEntity.MarketPrice;
            //    newSparePartEntity.MaterialNO = sparePartEntity.MaterialNO;
            //    newSparePartEntity.ModelNumber = sparePartEntity.ModelNumber;
            //    newSparePartEntity.Count = lendCount;
            //    newSparePartEntity.ProductType = sparePartEntity.ProductType;
            //    newSparePartEntity.ServiceStation = GetEntities<ServiceStation>().Where(s => s.ID == targetServiceStationEntity.ID).FirstOrDefault();
            //    newSparePartEntity.SparePartPrice = sparePartEntity.SparePartPrice;
            //    newSparePartEntity.StockType = sparePartEntity.StockType;
            //    newSparePartEntity.GoodCount = lendCount;

            //    newSparePartEntity.VersionNumber = sparePartEntity.VersionNumber;
            //    newSparePartEntity.StockPlace = sparePartEntity.StockPlace;
            //    newSparePartEntity.EnterNO = sparePartEntity.EnterNO;
            //    newSparePartEntity.EnterComment = sparePartEntity.EnterComment;
            //    InsertEntity(newSparePartEntity);
            //}
            //else
            //{
            //    sparePart.Count += lendCount;
            //    sparePart.LastUpdateBy = currentOperator.UserID;
            //    sparePart.LastUpdated = DateTime.Now;
            //    sparePart.GoodCount += lendCount;

            //    UpdateEntity(sparePart);
            //}
            
            //借出日志
            SparePartRecord sparePartRecordEntity = new SparePartRecord();
            sparePartRecordEntity.GoodCount = lendCount;
            sparePartRecordEntity.ModelNumber = sparePartEntity.ModelNumber;
            sparePartRecordEntity.VersionNumer = sparePartEntity.VersionNumber;
            sparePartRecordEntity.ServiceStation = GetEntities<ServiceStation>().Where(s => s.ID == sparePartEntity.ServiceStation.ID).FirstOrDefault(); 
            sparePartRecordEntity.Operator = currentOperator.UserID;
            sparePartRecordEntity.OperationType = string.Format("借出({0}->{1})", sparePartEntity.ServiceStation.Name, customerName);
            sparePartRecordEntity.OutCount = lendCount;
            sparePartRecordEntity.OutStorageDate = DateTime.Now;
            InsertEntity(sparePartRecordEntity);

            //借入操作方的入库记录
            //SparePartRecord inSparePartRecordEntity = new SparePartRecord();
            //inSparePartRecordEntity.GoodCount = lendCount;
            //inSparePartRecordEntity.ModelNumber = sparePartEntity.ModelNumber;
            //inSparePartRecordEntity.VersionNumer = sparePartEntity.VersionNumber;
            //inSparePartRecordEntity.ServiceStation = GetEntities<ServiceStation>().Where(s => s.ID == targetServiceStationEntity.ID).FirstOrDefault();
            //inSparePartRecordEntity.Operator = currentOperator.UserID;
            //inSparePartRecordEntity.OperationType = string.Format("借入({0}->{1})", sparePartEntity.ServiceStation.Name, targetServiceStationEntity.Name);
            //inSparePartRecordEntity.EnterCount = lendCount;
            //inSparePartRecordEntity.EnterStorageDate = DateTime.Now;
            //InsertEntity(inSparePartRecordEntity);

            // 借出记录（控制流程）
            SparePartLendRecord lendRecordEntity = new SparePartLendRecord();
            lendRecordEntity.Address = address;
            lendRecordEntity.ContactPerson = contactPerson;
            lendRecordEntity.CustomerName = customerName;
            lendRecordEntity.Email = email;
            lendRecordEntity.LastUpdateBy = currentOperator.UserID;
            lendRecordEntity.LastUpdated = DateTime.Now;
            lendRecordEntity.LendCount = lendCount;
            lendRecordEntity.LendDate = DateTime.Now;
            lendRecordEntity.LendDeadline = deadline;
            lendRecordEntity.ModelNumber = sparePartEntity.ModelNumber;
            lendRecordEntity.Phone = phone;
            lendRecordEntity.Status = "借用中";
            lendRecordEntity.VersionNumber = sparePartEntity.VersionNumber;
            lendRecordEntity.ServiceStation = GetEntities<ServiceStation>().Where(s => s.ID == sparePartEntity.ServiceStation.ID).FirstOrDefault();
            lendRecordEntity.LendReason = lendReason;
            lendRecordEntity.SparePart = sparePartEntity;
            lendRecordEntity.LendType = "客户借用";
            InsertEntity(lendRecordEntity);
        }

        public void SavePlatformLendRecord(int sparePartID, int lendCount, int lendPlatformID, DateTime deadline, User currentOperator, string lendReason)
        {
            SparePart sparePartEntity = GetEntities<SparePart>().Where(s => s.ID == sparePartID).FirstOrDefault();
            sparePartEntity.GoodCount -= lendCount;
            sparePartEntity.Count -= lendCount;
            sparePartEntity.LastUpdated = DateTime.Now;
            sparePartEntity.LastUpdateBy = currentOperator.UserID;
            UpdateEntity(sparePartEntity);

            if (!sparePartEntity.ServiceStationReference.IsLoaded)
            {
                sparePartEntity.ServiceStationReference.Load();
            }
            if (!sparePartEntity.ProductTypeReference.IsLoaded)
            {
                sparePartEntity.ProductTypeReference.Load();
            }
            if (!currentOperator.ServiceStationReference.IsLoaded)
            {
                currentOperator.ServiceStationReference.Load();
            }

            //借入单位备件存储信息
            SparePart sparePart = GetEntities<SparePart>().Where(s => s.ModelNumber.Equals(sparePartEntity.ModelNumber) 
                && s.VersionNumber.Equals(sparePartEntity.VersionNumber) && s.StockType.Equals(sparePartEntity.StockType)
                && s.ServiceStation.ID == lendPlatformID).FirstOrDefault();
            ServiceStationService serviceStationService = new ServiceStationService();
            ServiceStation targetServiceStationEntity = serviceStationService.GetServiceStation(lendPlatformID);
            if (sparePart == null)
            {
                SparePart newSparePartEntity = new SparePart();
                newSparePartEntity.LastUpdateBy = currentOperator.UserID;
                newSparePartEntity.LastUpdated = DateTime.Now;
                newSparePartEntity.MarketPrice = sparePartEntity.MarketPrice;
                newSparePartEntity.MaterialNO = sparePartEntity.MaterialNO;
                newSparePartEntity.ModelNumber = sparePartEntity.ModelNumber;
                newSparePartEntity.Count = lendCount;
                newSparePartEntity.ProductType = sparePartEntity.ProductType;
                newSparePartEntity.ServiceStation = GetEntities<ServiceStation>().Where(s => s.ID == targetServiceStationEntity.ID).FirstOrDefault();
                newSparePartEntity.SparePartPrice = sparePartEntity.SparePartPrice;
                newSparePartEntity.StockType = sparePartEntity.StockType;
                newSparePartEntity.GoodCount = lendCount;

                newSparePartEntity.VersionNumber = sparePartEntity.VersionNumber;
                newSparePartEntity.StockPlace = sparePartEntity.StockPlace;
                newSparePartEntity.EnterNO = sparePartEntity.EnterNO;
                newSparePartEntity.EnterComment = sparePartEntity.EnterComment;
                InsertEntity(newSparePartEntity);
            }
            else
            {
                sparePart.Count += lendCount;
                sparePart.LastUpdateBy = currentOperator.UserID;
                sparePart.LastUpdated = DateTime.Now;
                sparePart.GoodCount += lendCount;

                UpdateEntity(sparePart);
            }

            //借出日志
            SparePartRecord sparePartRecordEntity = new SparePartRecord();
            sparePartRecordEntity.GoodCount = lendCount;
            sparePartRecordEntity.ModelNumber = sparePartEntity.ModelNumber;
            sparePartRecordEntity.VersionNumer = sparePartEntity.VersionNumber;
            sparePartRecordEntity.ServiceStation = GetEntities<ServiceStation>().Where(s => s.ID == sparePartEntity.ServiceStation.ID).FirstOrDefault();
            sparePartRecordEntity.Operator = currentOperator.UserID;
            sparePartRecordEntity.OperationType = string.Format("借出({0}->{1})", sparePartEntity.ServiceStation.Name, targetServiceStationEntity.Name);
            sparePartRecordEntity.OutCount = lendCount;
            sparePartRecordEntity.OutStorageDate = DateTime.Now;
            InsertEntity(sparePartRecordEntity);

            //借入操作方的入库记录
            SparePartRecord inSparePartRecordEntity = new SparePartRecord();
            inSparePartRecordEntity.GoodCount = lendCount;
            inSparePartRecordEntity.ModelNumber = sparePartEntity.ModelNumber;
            inSparePartRecordEntity.VersionNumer = sparePartEntity.VersionNumber;
            inSparePartRecordEntity.ServiceStation = GetEntities<ServiceStation>().Where(s => s.ID == targetServiceStationEntity.ID).FirstOrDefault();
            inSparePartRecordEntity.Operator = currentOperator.UserID;
            inSparePartRecordEntity.OperationType = string.Format("借入({0}->{1})", sparePartEntity.ServiceStation.Name, targetServiceStationEntity.Name);
            inSparePartRecordEntity.EnterCount = lendCount;
            inSparePartRecordEntity.EnterStorageDate = DateTime.Now;
            InsertEntity(inSparePartRecordEntity);

            // 借出记录（控制流程）
            SparePartLendRecord lendRecordEntity = new SparePartLendRecord();
            lendRecordEntity.Address = targetServiceStationEntity.Address;
            lendRecordEntity.ContactPerson = targetServiceStationEntity.ContactPerson;
            lendRecordEntity.CustomerName = targetServiceStationEntity.Name;
            lendRecordEntity.Email = targetServiceStationEntity.EMail;
            lendRecordEntity.LastUpdateBy = currentOperator.UserID;
            lendRecordEntity.LastUpdated = DateTime.Now;
            lendRecordEntity.LendCount = lendCount;
            lendRecordEntity.LendDate = DateTime.Now;
            lendRecordEntity.LendDeadline = deadline;
            lendRecordEntity.ModelNumber = sparePartEntity.ModelNumber;
            lendRecordEntity.Phone = targetServiceStationEntity.Phone;
            lendRecordEntity.Status = "借用中";
            lendRecordEntity.VersionNumber = sparePartEntity.VersionNumber;
            lendRecordEntity.ServiceStation = GetEntities<ServiceStation>().Where(s => s.ID == sparePartEntity.ServiceStation.ID).FirstOrDefault();
            lendRecordEntity.LendReason = lendReason;
            lendRecordEntity.SparePart = sparePartEntity;
            lendRecordEntity.LendType = "平台借用";
            InsertEntity(lendRecordEntity);
        }

        public List<SparePartLendRecordModel> GetSparePartLendRecordsModel(User currenOperator, string keyword)
        {
            if (!currenOperator.ServiceStationReference.IsLoaded)
            {
                currenOperator.ServiceStationReference.Load();
            }

            List<SparePartLendRecordModel> lendModels = new List<SparePartLendRecordModel>();
            IQueryable<SparePartLendRecord> sparePartLendRecordsEntities = null;
            if (currenOperator.UserType.ID == (int)RoleType.Administrator)
            {
                sparePartLendRecordsEntities = GetEntities<SparePartLendRecord>();
            }
            else
            {
                sparePartLendRecordsEntities = GetEntities<SparePartLendRecord>().Where(l => l.ServiceStation.ID == currenOperator.ServiceStation.ID);
            }
            sparePartLendRecordsEntities = sparePartLendRecordsEntities.OrderBy(s => s.LendDate);
            foreach (SparePartLendRecord lendRecordEntity in sparePartLendRecordsEntities)
            {
                SparePartLendRecordModel lendRecordModel = new SparePartLendRecordModel();
                lendRecordModel.ID = lendRecordEntity.ID.ToString();
                lendRecordModel.Address = lendRecordEntity.Address;
                lendRecordModel.ContactPerson = lendRecordEntity.ContactPerson;
                lendRecordModel.Customer = lendRecordEntity.CustomerName;
                lendRecordModel.Deadline = lendRecordEntity.LendDeadline.ToShortDateString();
                lendRecordModel.Email = lendRecordEntity.Email;
                lendRecordModel.LendDate = lendRecordEntity.LendDate.ToShortDateString();
                lendRecordModel.Count = lendRecordEntity.LendCount.ToString();
                lendRecordModel.ModelNumber = lendRecordEntity.ModelNumber;
                lendRecordModel.Phone = lendRecordEntity.Phone;
                lendRecordModel.VersionNumber = lendRecordEntity.VersionNumber;
                lendRecordModel.Status = lendRecordEntity.Status;
                lendRecordModel.Reason = lendRecordEntity.LendReason;
                lendRecordModel.LendType = lendRecordEntity.LendType;
                if (!lendRecordEntity.Status.Equals("已归还"))
                {
                    if (lendRecordEntity.LendDeadline > DateTime.Now)
                    {
                        lendRecordModel.ExceedDays = "";
                    }
                    else
                    {
                        int exceedDays = DateTimeService.CalculateDateTimeSpan(lendRecordEntity.LendDeadline, DateTime.Now);
                        if (exceedDays > 0)
                        {
                            lendRecordModel.ExceedDays = "!" + exceedDays.ToString();
                        }
                    }
                }
                if (!lendRecordEntity.ServiceStationReference.IsLoaded)
                {
                    lendRecordEntity.ServiceStationReference.Load();
                }
                lendRecordModel.Platform = lendRecordEntity.ServiceStation.Name;
                lendRecordModel.BackComment = lendRecordEntity.BackComment;
                lendModels.Add(lendRecordModel);
            }

            if (!string.IsNullOrEmpty(keyword))
            {
                lendModels = lendModels.Where(a => (null != a.VersionNumber && a.VersionNumber.Contains(keyword))
                    || (null != a.Deadline && a.Deadline.Contains(keyword))
                    || (null != a.LendDate && a.LendDate.Contains(keyword))
                    || (null != a.ExceedDays && a.ExceedDays.Contains(keyword))
                    || (null != a.Count && a.Count.Contains(keyword))
                    || (null != a.ModelNumber && a.ModelNumber.Contains(keyword))
                    || (null != a.ContactPerson && a.ContactPerson.Contains(keyword))
                    || (null != a.Customer && a.Customer.Contains(keyword))
                    || (null != a.Email && a.Email.Contains(keyword))
                    || (null != a.Phone && a.Phone.Contains(keyword))
                    || (null != a.Address && a.Address.Contains(keyword))
                    || (null != a.Reason && a.Reason.Contains(keyword))
                    || (null != a.Status && a.Status.Contains(keyword))
                    || (null != a.Platform && a.Platform.Contains(keyword))).ToList();
            }

            return lendModels;
        }

        public SparePartLendRecord GetLendRecordByID(int id)
        {
            return GetEntities<SparePartLendRecord>().Where(s => s.ID == id).FirstOrDefault();
        }

        public void BackSparePart(int id, User currentOperator, string backType, string backVersion, int backCount, string backComment)
        {
            SparePartLendRecord lendRecordEntity = GetEntities<SparePartLendRecord>().Where(s => s.ID == id).FirstOrDefault();
            if (!lendRecordEntity.SparePartReference.IsLoaded)
            {
                lendRecordEntity.SparePartReference.Load();
            }
            if (!lendRecordEntity.ServiceStationReference.IsLoaded)
            {
                lendRecordEntity.ServiceStationReference.Load();
            }

            if (!currentOperator.ServiceStationReference.IsLoaded)
            {
                currentOperator.ServiceStationReference.Load();
            }
            SparePart rtnSparePartEntity = new SparePart();
            if (lendRecordEntity.LendType.Equals("平台借用"))
            {
                ServiceStationService serviceStationService = new ServiceStationService();
                ServiceStation lendinServiceStation = serviceStationService.GetServiceStationByName(lendRecordEntity.CustomerName);
                //归还方备件减少统计记录
                rtnSparePartEntity = GetEntities<SparePart>().Where(p => p.ModelNumber == backType
                    && p.VersionNumber == backVersion && p.StockType == lendRecordEntity.SparePart.StockType
                    && p.ServiceStation.ID == lendinServiceStation.ID).FirstOrDefault();
                if (null != rtnSparePartEntity)
                {
                    if (rtnSparePartEntity.Count < backCount)
                    {
                        throw new Exception(string.Format("归还备件的存储数量只有{0}，请先手动增加备件!", rtnSparePartEntity.Count));
                    }
                    //sparePartEntity2.GoodCount -= lendRecordEntity.LendCount;
                    //sparePartEntity2.Count -= lendRecordEntity.LendCount;
                    rtnSparePartEntity.GoodCount -= backCount;
                    rtnSparePartEntity.Count -= backCount;
                    rtnSparePartEntity.LastUpdated = DateTime.Now;
                    rtnSparePartEntity.LastUpdateBy = currentOperator.UserID;
                    UpdateEntity(rtnSparePartEntity);
                }
                else
                {
                    throw new Exception("系统内无归还备件的存储信息，请先手动增加新备件!");
                }
            }

            
            lendRecordEntity.Status = "已归还";
            lendRecordEntity.LastUpdated = DateTime.Now;
            lendRecordEntity.LastUpdateBy = currentOperator.UserID;
            lendRecordEntity.BackComment = backComment;
            UpdateEntity(lendRecordEntity);

            SparePart sparePartEntity = GetEntities<SparePart>().Where(p => p.ModelNumber == backType
                && p.VersionNumber == backVersion && p.StockType == lendRecordEntity.SparePart.StockType
                && p.ServiceStation.ID == lendRecordEntity.ServiceStation.ID).FirstOrDefault();
            if (null != sparePartEntity)
            {
                sparePartEntity.GoodCount += backCount;
                sparePartEntity.Count += backCount;
                sparePartEntity.LastUpdated = DateTime.Now;
                sparePartEntity.LastUpdateBy = currentOperator.UserID;
                UpdateEntity(sparePartEntity);
            }
            //else
            //{
            //    if (!rtnSparePartEntity.ProductTypeReference.IsLoaded)
            //    {
            //        rtnSparePartEntity.ProductTypeReference.Load();
            //    }
            //    SparePart addSparePartEntity = new SparePart();
            //    addSparePartEntity.ModelNumber = backType;
            //    addSparePartEntity.ProductType = GetEntities<ProductType>().Where(s => s.ProductTypeID == rtnSparePartEntity.ProductType.ProductTypeID).FirstOrDefault();
            //    addSparePartEntity.ServiceStation = GetEntities<ServiceStation>().Where(s => s.ID == lendRecordEntity.ServiceStation.ID).FirstOrDefault();
            //    addSparePartEntity.StockType = rtnSparePartEntity.StockType;

            //    addSparePartEntity.VersionNumber = backVersion;
            //    addSparePartEntity.StockPlace = rtnSparePartEntity.StockPlace;

            //    addSparePartEntity.GoodCount = backCount;
            //    addSparePartEntity.Count = backCount;
            //    addSparePartEntity.LastUpdated = DateTime.Now;
            //    addSparePartEntity.LastUpdateBy = currentOperator.UserID;

            //    addSparePartEntity.MarketPrice = rtnSparePartEntity.MarketPrice;
            //    addSparePartEntity.MaterialNO = rtnSparePartEntity.MaterialNO;
            //    addSparePartEntity.SparePartPrice = rtnSparePartEntity.SparePartPrice;
            //    InsertEntity(addSparePartEntity);
            //}

            
                

            SparePartRecord enterRecordEntity = new SparePartRecord();
            enterRecordEntity.EnterStorageDate = DateTime.Now;
            //recordEntity.EnterCount = lendRecordEntity.LendCount;
            //recordEntity.GoodCount = lendRecordEntity.LendCount;
            //recordEntity.ModelNumber = lendRecordEntity.ModelNumber;
            //recordEntity.VersionNumer = lendRecordEntity.VersionNumber;
            enterRecordEntity.EnterCount = backCount;
            enterRecordEntity.GoodCount = backCount;
            enterRecordEntity.ModelNumber = backType;
            enterRecordEntity.VersionNumer = backVersion;
            enterRecordEntity.Comment = backComment;
            enterRecordEntity.OperationType = string.Format("归还({0}->{1})", lendRecordEntity.CustomerName, lendRecordEntity.ServiceStation.Name);
            enterRecordEntity.Operator = currentOperator.UserID;
            enterRecordEntity.ServiceStation = GetEntities<ServiceStation>().Where(s => s.ID == lendRecordEntity.ServiceStation.ID).FirstOrDefault();
            InsertEntity(enterRecordEntity);

            if (lendRecordEntity.LendType.Equals("平台借用"))
            {
                ServiceStationService serviceStationService = new ServiceStationService();
                ServiceStation lendinServiceStation = serviceStationService.GetServiceStationByName(lendRecordEntity.CustomerName);

                //增加归还方备件减少流动记录
                SparePartRecord OutRecordEntity = new SparePartRecord();
                OutRecordEntity.OutStorageDate = DateTime.Now;
                //recordEntity2.OutCount = lendRecordEntity.LendCount;
                //recordEntity2.GoodCount = lendRecordEntity.LendCount;
                //recordEntity2.ModelNumber = lendRecordEntity.ModelNumber;
                //recordEntity2.VersionNumer = lendRecordEntity.VersionNumber;
                OutRecordEntity.OutCount = backCount;
                OutRecordEntity.GoodCount = backCount;
                OutRecordEntity.ModelNumber = backType;
                OutRecordEntity.VersionNumer = backVersion;
                OutRecordEntity.Comment = backComment;
                OutRecordEntity.OperationType = string.Format("归还({0}->{1})", lendinServiceStation.Name, lendRecordEntity.ServiceStation.Name);
                OutRecordEntity.Operator = currentOperator.UserID;
                OutRecordEntity.ServiceStation = GetEntities<ServiceStation>().Where(s => s.ID == currentOperator.ServiceStation.ID).FirstOrDefault();
                InsertEntity(OutRecordEntity);
            }
        }

        public List<SparePartModel> SearchSpareParts(string materialNumber, string modelNumber, string versionNumber, int platformID, string badOrGood)
        {
            List<SparePartModel> resultList = new List<SparePartModel>();
            IQueryable<SparePart> allSpareParts = GetEntities<SparePart>();
            if (!string.IsNullOrEmpty(materialNumber) && allSpareParts != null)
            {
                allSpareParts = allSpareParts.Where(s => s.MaterialNO.Contains(materialNumber));
            }

            if (!string.IsNullOrEmpty(modelNumber) && allSpareParts != null)
            {
                allSpareParts = allSpareParts.Where(s => s.ModelNumber.Contains(modelNumber));
            }

            if (!string.IsNullOrEmpty(versionNumber) && allSpareParts != null)
            {
                allSpareParts = allSpareParts.Where(s => s.VersionNumber.Contains(versionNumber));
            }

            if (platformID != 0 && allSpareParts != null)
            {
                allSpareParts = allSpareParts.Where(s => s.ServiceStation.ID == platformID);
            }

            if (allSpareParts != null)
            {
                foreach (SparePart sparePartEntity in allSpareParts)
                {
                    SparePartModel sparePartModel = new SparePartModel();
                    sparePartModel.BadCount = sparePartEntity.BadCount.ToString();
                    sparePartModel.Count = sparePartEntity.Count.ToString();
                    sparePartModel.Description = sparePartEntity.Description;
                    sparePartModel.GoodCount = sparePartEntity.GoodCount.ToString();
                    sparePartModel.ID = sparePartEntity.ID.ToString();
                    sparePartModel.MarketPrice = sparePartEntity.MarketPrice;
                    sparePartModel.MaterialNO = sparePartEntity.MaterialNO;
                    sparePartModel.ModelNumber = sparePartEntity.ModelNumber;
                    sparePartModel.SparePartPrice = sparePartEntity.SparePartPrice;
                    if (!sparePartEntity.ServiceStationReference.IsLoaded)
                    {
                        sparePartEntity.ServiceStationReference.Load();
                    }
                    sparePartModel.Station = sparePartEntity.ServiceStation.Name;
                    sparePartModel.VersionNumber = sparePartEntity.VersionNumber;
                    if (!badOrGood.Equals("良品") && !badOrGood.Equals("非良品"))
                    {
                        resultList.Add(sparePartModel);
                    }
                    else if ((badOrGood == "良品" && sparePartEntity.GoodCount > 0) || (badOrGood == "非良品" && sparePartEntity.BadCount > 0))
                    {
                        resultList.Add(sparePartModel);
                    }                  
                }
            }
            return resultList;
        }

        public void UpdateSparePart(SparePart sp)
        {
            UpdateEntity(sp);
        }
    }
}
